package com.dwcode.macro.controller;

import com.dwcode.macro.dto.ResultInfo;
import com.dwcode.macro.entity.Emp;
import com.dwcode.macro.entity.TUser;
import com.dwcode.macro.service.TUserService;
import com.fasterxml.jackson.databind.util.JSONPObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

@Controller
@Slf4j
//@RequestMapping("/admin")
public class LoginController {

    @Autowired
    private TUserService userService;

    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }
    @GetMapping("/register")
    public String registerPage() {
        return "register";
    }

    @PostMapping("/login")
    public String resultInfo(String username, String password, HttpSession session) {
        log.info(username + password);
        TUser tUser = userService.findUserByNameAndPassword(username, password);
        if (tUser != null) {
            session.setAttribute("user", tUser);
            session.setAttribute("emp", new Emp(9527, "zhouzhuo", "Boss"));
            return "redirect:index";
        }
        return "redirect:login";
    }

    @PostMapping("/register")
    public String register(TUser user, Model model) {
        log.info("user:" + user);
        TUser tUser = userService.insert(user);
        if (tUser != null){
            model.addAttribute("msg","注册成功");
            return "redirect:/login";
        }else{
            model.addAttribute("msg","注册失败");
            return "redirect:/register";
        }

    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/login";
    }

    @GetMapping("/validation")
    public @ResponseBody ResultInfo validation(TUser user){
        ResultInfo<Object> info = new ResultInfo<>();
        List<TUser> userSearch = userService.queryAll(user);
        if (userSearch.size() > 0){
            info.setCode(0);
            info.setMsg("该邮箱已注册");
        }else{
            info.setCode(1);
            info.setMsg("邮箱可用");
        }
        return info;
    }
}


